package com.lib.framework.network.adapter.request

import com.lib.framework.manager.thread.mainThreadRun
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * Copyright (C), 2019-2020
 * FileName: ApiRequest
 * Author: Kevin
 * Date: 2020-01-06 16:59
 * Description: api 请求类，T 是返回结果的类型
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class ApiRequest<T>(private val call: Call<T>) {

    /**
     * 异步请求
     */
    fun request(callBack: ApiRequestCallback<T>) {
        call.enqueue(object : Callback<T> {

            override fun onFailure(call: Call<T>, t: Throwable) {
                mainThreadRun {
                    callBack.onFailure(t)
                }
            }

            override fun onResponse(call: Call<T>, response: Response<T>) {
                mainThreadRun {
                    callBack.onSuccess(response.body())
                }
            }
        })
    }

    /**
     * 同步请求
     */
    fun requestSynchronously(callBack: ApiRequestCallback<T>) {
        try {
            val response = call.execute()
            callBack.onSuccess(response.body())
        } catch (e: Exception) {
            callBack.onFailure(Throwable(e))
        }
    }
}

